<template>
  <div class="outer-container">
    <div class="scroll-container">
      <!-- 多选框最少有一个 -->
      <div style="display: flex;    align-items: flex-end;position: absolute;top: -8px">
        <el-checkbox-group v-model="checkList" @change="handleCheckChange">
          <el-checkbox label="品牌"></el-checkbox>
          <el-checkbox label="类型"></el-checkbox>
          <el-checkbox label="端口"></el-checkbox>
          <el-checkbox label="脆弱点"></el-checkbox>
          <el-checkbox label="漏洞类型"></el-checkbox>
        </el-checkbox-group>
       <div style="margin-left: 50px;">
        <el-tag v-for="tag in checkList" :key="tag" closable :type="'success'" @close="handleClose(tag)">
          {{ tag }}
        </el-tag>
       </div>
      </div>
      <div ref="treeChart" class="tree-chart"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { getGraphNew } from "@/api/system/info";

export default {
  name: "RelationshipNew",
  props: {
    queryParams: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      tags: [
        { name: "标签一", type: "" },
        { name: "标签二", type: "success" },
        { name: "标签三", type: "info" },
        { name: "标签四", type: "warning" },
        { name: "标签五", type: "danger" },
      ],
      chart: null,
      treeData: {},
      checkList: [],
      lastCheckList: [],
      selectCheck: [
        {
          name: "类型",
          value: "camera_type",
        },
        {
          name: "品牌",
          value: "camera_brand",
        },
        {
          name: "端口",
          value: "camera_port",
        },
        {
          name: "脆弱点",
          value: "camera_fra_point",
        },
        {
          name: "漏洞类型",
          value: "camera_loophole",
        },
      ],
    };
  },
  mounted() {
    this.checkList = ["品牌"];
    this.lastCheckList = ["品牌"];
    //发送网络请求获取数据
    this.queryData();
    // 使用 nextTick 确保 DOM 已经渲染完成
    // this.$nextTick(() => {
    //   this.initChart()
    // })
    window.addEventListener("resize", this.resizeChart);
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    window.removeEventListener("resize", this.resizeChart);
    // 销毁图表实例
    this.chart && this.chart.dispose();
  },
  methods: {
    handleClose(tag){
      //  this.checkList
    },

    handleCheckChange(value) {
      console.log(value);
      //如果只有一个数据，提醒必须有一个选中
      if (value.length === 0) {
        this.$message.warning("请至少选择一个选项");
        this.checkList = this.lastCheckList;
        return;
      }
      this.lastCheckList = value;
      this.queryData();
    },
    queryData() {
      console.log("queryParamsqueryParams", this.queryParams);
      if (this.checkList.length > 0) {
        let reqData = [];
        this.checkList.forEach((item) => {
          reqData.push(this.selectCheck.find((check) => check.name === item));
        });
        console.log(reqData);
        getGraphNew({ selectCheck: reqData }).then((res) => {
          if (res.code === 200) {
            this.treeData = res.data;
            this.initChart();
          }
        });
      } else {
        this.getGraphNewFn();
      }
    },
    getGraphNewFn() {
      getGraphNew().then((res) => {
        console.log(res);
        if (res.code === 200) {
          this.treeData = res.data;
          this.initChart();
        }
      });
    },

    handleNodeClick(params) {
      // 判断是否为叶子节点（没有children或children长度为0）
      if (!params.data.children || params.data.children.length === 0) {
        this.$emit("clickCamera", params.data.info);
      }
    },

    initChart() {
      //判断有无实例对象
      if (this.chart) {
        this.chart.dispose();
      }
      const container = this.$refs.treeChart;
      // 设置一个固定的宽度，确保有足够的空间显示所有节点
      const containerWidth = 2000; // 固定宽度
      const containerHeight = container.clientHeight || 600;

      this.chart = echarts.init(container, null, {
        width: containerWidth,
        height: containerHeight,
      });
      const option = {
        tooltip: {
          trigger: "item",
          triggerOn: "mousemove",
          backgroundColor: "rgba(255,255,255,0.95)",
          borderColor: "#ccc",
          borderWidth: 1,
          padding: [10, 15],
          textStyle: {
            color: "#333",
          },
          formatter: function (params) {
            const data = params.data;
            let result = "";
            // 遍历对象的所有属性并换行显示
            for (let key in data) {
              if (
                key !== "children" &&
                data[key] !== null &&
                data[key] !== undefined
              ) {
                result += `${key}：${data[key]}<br/>`;
              }
            }
            return result;
          },
        },
        series: [
          {
            type: "tree",
            data: [this.treeData],
            top: "5%",
            left: "5%",
            bottom: "5%",
            right: "5%",
            symbolSize: 7,
            orient: "LR",
            roam: false, // 禁用缩放和平移
            initialTreeDepth: 6, // 默认展开6层
            label: {
              position: "top",
              verticalAlign: "bottom",
              align: "center",
              fontSize: 14,
              color: "#333",
              padding: [0, 8, 8, 8], // 上右下左的内边距
              distance: 10, // 标签与节点的距离
            },
            leaves: {
              label: {
                position: "top",
                verticalAlign: "bottom",
                align: "center",
                fontSize: 14,
                padding: [0, 8, 8, 8],
              },
            },
            emphasis: {
              focus: "descendant",
            },
            expandAndCollapse: true,
            animationDuration: 550,
            animationDurationUpdate: 750,
            layoutAnimation: true,
            itemStyle: {
              borderWidth: 1,
            },
            lineStyle: {
              width: 1,
              curveness: 0.5,
            },
          },
        ],
      };
      this.chart.setOption(option);

      // 绑定点击事件
      this.chart.on("click", this.handleNodeClick);
    },
    resizeChart() {
      this.chart && this.chart.resize();
    },
    // 更新图表数据的方法
    updateChartData(newData) {
      if (this.chart) {
        const option = this.chart.getOption();
        option.series[0].data = [newData];
        this.chart.setOption(option);
      }
    },
  },
};
</script>

<style scoped>
.outer-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.scroll-container {
  width: 100%;
  height: 100%;
  overflow-x: auto;
  overflow-y: hidden;
}

.tree-chart {
  height: 100%;
  min-width: 100%;
}

/* 自定义滚动条样式 */
.scroll-container::-webkit-scrollbar {
  height: 8px;
}

.scroll-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.scroll-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.scroll-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>
